import axios from 'axios'
import { stringify } from 'qs'
import { message } from 'ant-design-vue'
const service = axios.create({
  baseURL: '/api/',
  timeout: 8000, // 请求超时时间
  withCredentials: true
})
const name = 'test'
service.interceptors.request.use(config => {
  const token = window.localStorage.getItem('access-token')
  if (token) {
    config.headers['token'] = token
  }
  return config
}, error => {
  return Promise.reject(error)
})

service.interceptors.response.use((response) => {
  const res = response.data.data
  const msg = response.data.message
  if (response.data.code !== 200) {
    if ( msg === '用户未登录' || msg === '请先登录') {
      window.localStorage.removeItem('access-token')
      window.localStorage.removeItem('user-info')
      return message.error('登录失效，请重新登录')
    }
    console.log(msg)
    return Promise.reject(msg || 'error')
  }
  return res
}, error => {
  return Promise.reject(error)
})
const serviceMethod = (params) => {
  const method = (params.method ? params.method : 'get').toLowerCase()
  params.data = checkParams(params.data)
  let res
  switch (method) {
    case 'get':
      if (params.data && Object.keys(params.data).length > 0) {
        params.url += ('?' + stringify(params.data || {}))
      }
      res = service[method](params.url)
      break
    case 'post':
      if (params.dataType === 'payload') {
        res = service[method](params.url, params.data || {})
      } else {
        const fd = new FormData()
        if (params.data) {
          for (const k in params.data) {
            fd.append(k, params.data[k])
          }
        }
        res = service[method](params.url, fd)
      }
      break
    case 'delete':
      params.data = params.data || {}
      if (params.dataType === 'payload') {
        res = service[method](params.url, { data: params.data })
      } else {
        params.url += ('?' + stringify(params.data))
        res = service[method](params.url)
      }
      break
    default:
      res = '参数错误'
      break
  }
  return Promise.resolve(res)

}

// 过滤data参数
const checkParams = (data) => {
  data = data || {}
  for (const k in data) {
    if (data[k] === undefined) {
      delete data[k]
    }
  }
  return data
}

export {
  serviceMethod as axios
}
